<template>
  <div class="app-container">
    <el-card shadow="hover">
      <div slot="header" style="
          font-size: larger;
          color: #909399;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 40px;
        ">
        Dw迁移助手导出包解析
      </div>

      <!-- 文件上传区域 -->
      <div class="upload-area">
        <el-upload ref="upload" action="" :auto-upload="false" :on-change="handleFileChange" :show-file-list="false"
          accept=".zip">
          <el-button size="small" type="primary">选择投产包</el-button>
          <div v-if="fileName" class="file-info">
            <i class="el-icon-document"></i>
            {{ fileName }} ({{ fileSize }})
          </div>
          <div v-else class="file-tip">未选择任何文件</div>
        </el-upload>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" :disabled="!file" @click="parseFile" :loading="loading">
          解析投产包
        </el-button>
        <el-button @click="reset">重置</el-button>
      </div>

      <!-- 解析结果展示 -->
      <div v-if="resultVisible" class="result-container">
        <h3>解析结果：</h3>

        <!-- 树状结构展示 -->
        <el-tree :data="treeData" :props="treeProps" node-key="id" :expand-on-click-node="false"
          :render-content="renderContent" class="tree-container"></el-tree>
      </div>
    </el-card>
  </div>
</template>

<script>
import { fileUploadParser } from "@/api/bigdata/dataWorks";

export default {
  name: "ZipParser",
  data() {
    return {
      file: null,
      fileName: "",
      fileSize: "",
      loading: false,
      parseResult: [],
      resultVisible: false,
      treeData: [], // 树状结构数据
      treeProps: { // 树结构配置
        children: "children",
        label: "label"
      }
    };
  },
  methods: {
    // 文件选择处理
    handleFileChange(file) {
      if (
        file.raw.type !== "application/zip" &&
        !file.raw.name.toLowerCase().endsWith(".zip")
      ) {
        this.$message.error("仅支持ZIP格式文件");
        return;
      }

      this.file = file.raw;
      this.fileName = file.name;
      this.fileSize = this.formatFileSize(file.size);
    },

    // 解析文件
    parseFile() {
      if (!this.file) {
        this.$message.warning("请先选择文件");
        return;
      }

      this.loading = true;
      this.resultVisible = true;
      this.parseResult = [];

      const formData = new FormData();
      formData.append("file", this.file);

      fileUploadParser(formData)
        .then(response => {
          if (response.code === 200) {
            try {
              // 解析并转换数据结构
              const rawData = typeof response.data === "string"
                ? JSON.parse(response.data)
                : response.data;

              this.parseResult = rawData;
              this.convertToTreeData(rawData); // 转换为树结构
              this.$message.success("解析成功");
            } catch (error) {
              console.error("数据解析失败:", error);
              this.$message.error("数据格式异常，请检查服务端返回");
            }
          } else {
            this.$message.error(response.msg || "解析失败");
          }
        })
        .catch(error => {
          this.$message.error("请求失败: " + error.message);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 重置状态
    reset() {
      this.file = null;
      this.fileName = "";
      this.fileSize = "";
      this.parseResult = [];
      this.treeData = [];
      this.resultVisible = false;
      this.$refs.upload.clearFiles();
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return "0 B";
      const k = 1024;
      const sizes = ["B", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
    },

    // 转换为树状结构数据
    convertToTreeData(workflows) {
      this.treeData = workflows.map((workflow, wIndex) => ({
        id: `workflow-${wIndex}`,
        type: "workflow",
        label: `工作流：${workflow.workFlow || "未命名"}`,
        children: workflow.taskList.map((task, tIndex) => ({
          id: `task-${wIndex}-${tIndex}`,
          type: "task",
          label: `任务：${task.taskName || "未命名"}`,
          children: task.params.map((param, pIndex) => ({
            id: `param-${wIndex}-${tIndex}-${pIndex}`,
            type: "param",
            label: `${param.param}`,
            value: param.value // 存储值用于渲染
          }))
        }))
      }));
    },

    // 自定义节点渲染
    renderContent(h, { node, data }) {
      switch (data.type) {
        case "workflow":
        case "task":
          return h("span", {}, [node.label]);

        case "param":
          return h("span", { class: "param-item" }, [
            h("span", { class: "param-key" }, `${data.label}：`),
            h("span", { class: "param-value" }, data.value)
          ]);

        default:
          return h("span", {}, [node.label]);
      }
    }
  }
};
</script>

<style scoped>
.upload-area {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  text-align: center;
  background-color: #fafafa;
}

.file-info {
  margin-top: 10px;
  color: #606266;
}

.file-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.action-buttons {
  margin: 20px 0;
  text-align: center;
}

.result-container {
  margin-top: 30px;
}

.tree-container {
  margin-top: 20px;
  border: 1px solid #ebedf0;
  border-radius: 4px;
}

.el-tree .el-tree-node {
  padding: 8px 16px;
}

.param-item {
  display: flex;
  align-items: center;
  white-space: normal;
}

.param-key {
  font-weight: 500;
  color: #606266;
  min-width: 120px;
  text-align: right;
  margin-right: 10px;
}

.param-value {
  color: #303133;
}
</style>